#include <pspkernel.h>
#include <pspdebug.h>
#include "shin_log.h"
#include <stdio.h>
#include <stdarg.h>
#include "config.h"

void log_init() __attribute__((constructor));
void log_destroy() __attribute__((destructor));

SceUID log_mutex;

void log_init()
{
#ifdef shin_log_enable
	log_mutex = sceKernelCreateSema("log mutex", 0, 1, 1, 0);
#ifdef shin_log_to_screen
	pspDebugScreenInit();
#endif
#endif
}

void log_destroy()
{
#ifdef shin_log_enable
	sceKernelDeleteSema(log_mutex);
#endif
}

char buffer2[shin_log_buffer_size];
char buffer[shin_log_buffer_size];

void shin_log(int level, const char* fmt, ...)
{
#ifdef shin_log_enable
	va_list arg;
#ifdef shin_log_to_file
	SceUID log_file;
#endif

//	if(level < shin_log_level)return;
	va_start(arg, fmt);
	sceKernelWaitSema(log_mutex, 1, 0);
	vsnprintf(buffer, shin_log_buffer_size, fmt, arg);
#ifdef shin_log_to_stdout
	printf("%s\n", buffer);
#endif
#ifdef shin_log_to_screen
	pspDebugScreenPrintf("%s\n", buffer);
#endif
#ifdef shin_log_to_file
	log_file = sceIoOpen(shin_log_file_name, PSP_O_CREAT | PSP_O_APPEND | PSP_O_WRONLY, 0777);
	sceIoWrite(log_file, buffer2, snprintf(buffer2, shin_log_buffer_size, "%s\r\n", buffer));
	sceIoClose(log_file);
#endif
	if(level == LOG_LEVEL_FATAL)sceKernelSleepThread();
	sceKernelSignalSema(log_mutex, 1);
	va_end(arg);
#endif
}
